package org.contacts.dao.impl;

import org.contacts.dao.Contact;
import org.contacts.dao.util.ConnectionFactory;

import java.sql.*;
import java.util.ArrayList;

/**
 * Created by nnazarov on 3/28/14.
 */
public class ContactModel {

    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    public ContactModel(){
        try {
            connection = ConnectionFactory.getConnecion();
            statement = connection.createStatement();
        }
        catch (SQLException se) {
            se.printStackTrace();
        }
    }

    public ArrayList<Contact> getAllContacts() {
        ArrayList<Contact> contacts = new ArrayList<Contact>();
        ContactDBA contactDBA = new ContactDBA();
        String query = contactDBA.getSelect(); //"SELECT * from contact";

        try {
            if (statement.execute(query)) {
                resultSet = statement.getResultSet();
                while (resultSet.next()) {
                    contactDBA.fill(resultSet);
                    ContactDAO contactDAO = new ContactDAO();
                    contactDBA.loadDAO(contactDAO);

                    Contact contact = new Contact();
                    contact.setFname(contactDAO.getFname_());
                    contact.setLname(contactDAO.getLname_());
                    contact.setPhone(contactDAO.getPhone_());
                    contacts.add(contact);
                }
            }
            else {
//                System.out.println("Selection failed");
            }
        }
        catch (SQLException se) {
//            System.out.println("Something is wrong with statement or query");
            se.printStackTrace();
        }
        return contacts;
    }
}
